import Vue from "vue"
import Vuex from "vuex"
import { getProductClassifyData } from "@/api/productlist"
Vue.use(Vuex)

let state = {
    productClassifyData : []
}

let mutations = {
    //根据分类获取产品列表
    "GET_PRODUCTCLASSIFYDATA" (state,{data,is,more}) {
        if(more === true) {
            if(is === false){ //false降序
                data = data.sort((a,b)=>{
                    return b.price - a.price
                })
            } else if(is === true) { //true升序
                data = data.sort((a,b)=>{
                    return a.price - b.price
                })
            }
        } else {
            if(data.length > 8) { //没点加载更多之前，只加载8条数据
                data = data.slice(0,8)
            }
            if(is === false){ //false降序
                data = data.sort((a,b)=>{
                    return b.price - a.price
                })
            } else if(is === true) { //true升序
                data = data.sort((a,b)=>{
                    return a.price - b.price
                })
            }
        }
        state.productClassifyData = data
    }
}

let actions = {
    //根据分类获取产品列表
    async getProductClassifyData({commit},{...val}) {
        let r = await getProductClassifyData({cid:val.id})
        commit("GET_PRODUCTCLASSIFYDATA",{data:r.data})
    },
    //加载更多
    async loadMore({commit},{...val}) {
        let r = await getProductClassifyData({cid:val.id})
        commit("GET_PRODUCTCLASSIFYDATA",{data:r.data,is:val.is,more:true})
    },
    //价格排序
    async priceSort({commit},{...val}) {
        let r = await getProductClassifyData({cid:val.id})
        commit("GET_PRODUCTCLASSIFYDATA",{data:r.data,is:val.is})
    }
}

let getters = {}

export default {
    namespaced : true,
    state,
    mutations,
    actions,
    getters
}